package com.example.test.advice.第五章_数组和集合.建议75_集合中的元素必须做到compareTo和equals同步;

import com.google.common.base.Objects;
import org.apache.commons.lang3.builder.CompareToBuilder;
import org.apache.commons.lang3.builder.EqualsBuilder;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * indexOf使用的是equals方法，binarySearch使用的是compareTo方法比较，City类中的
 * equals方法和compareTo方法相等条件不一致，故结果不一样，所以一定要保证equals方法
 * 和compareTo方法相等条件一致
 */
public class Client {

    public static void main(String[] args) {
        List<City> cities = new ArrayList<>();
        cities.add(new City("021","上海"));
        cities.add(new City("021","沪"));
        //排序
        Collections.sort(cities);
        //查找对象
        City city = new City("021","沪");
        //indexOf方法取得索引值
        int index1 = cities.indexOf(city);
        //binarySearch方法查找到索引值
        int index2 = Collections.binarySearch(cities,city);
        System.out.println("索引值（indexOf）="+index1);
        System.out.println("索引值（binarySearch）="+index2);
    }
}

class City implements Comparable<City>{

    //城市编码
    private String code;

    //城市姓名
    private String name;

    public City(String code, String name) {
        this.code = code;
        this.name = name;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public int compareTo(City o) {
        return new CompareToBuilder().append(name,o.name).toComparison();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        City city = (City) o;
        //return Objects.equal(code, city.code) && Objects.equal(name, city.name);
        return new EqualsBuilder().append(code,city.code).isEquals();
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(code, name);
    }
}
